#!/bin/sh
set -uxe
echo "`date`"
echo "Start make TQE"

export HOME="/root"
TQEDIR="/usr1/jenkins/plugins/CodeDEX_V3/tool/tools/coverity"
FORTIFYDIR="/usr1/jenkins/plugins/CodeDEX_V3/tool/tools/fortify"
BINSCOPEDIR="/usr1/jenkins/plugins/CodeDEX_V3/tool/tools/binscope"
CI_PROJECT=`pwd | awk -F'/' '{print $(NF-2)}'`
CPATH="/usr1/CISrc/${CI_PROJECT}"
TMPCPATH=`pwd`
OBSSERVER_IP="100.109.85.100"
set +u
if [ "x${obs_server_from_jenkins}" != "x" ]; then
    OBSSERVER_IP="${obs_server_from_jenkins}"
fi
set -u

function init_osc()
{
    set +e
    rm -f /root/.config/osc/trusted-certs/euleros-obs_443.pem
    if which osc &> /dev/null; then
        log_info "osc has been here"
    else
        url1="http://10.175.100.158/iso/SLE:/12:/SP2/SLE-12-SP2-SDK-DVD-x86_64-GM-DVD1"
        url2="http://10.175.100.158/iso/SLE:/12:/SP2/SLE-12-SP2-Server-DVD-x86_64-GM-DVD1"

        repo=`zypper lr | awk '{if(NR>2)print $1}'`
        if [ -n "$repo" ];then
            zypper rr $repo
        fi

        zypper ar $url1 sdk
        zypper ar $url2 dvd
        zypper ref -f
        zypper --non-interactive install osc
    fi
    
    cat << EOF > /root/.oscrc
[general]
apiurl = https://euleros-obs
no_verify = 1

[https://euleros-obs]
user=root
pass=EulerOS_123
EOF

    expect -c "
        set timeout 300
        spawn osc ls SUSE:SLE-11:SP3
            expect {
                \"Enter choice*:\" {send \"2\r\"; exp_continue}
            }
    "
    osc ls SUSE:SLE-11:SP3
    if [ $? -ne 0 ]; then
        log_error "failed: when osc ls SUSE:SLE-11:SP3"
    fi
    set -e
}

function check_env()
{
    if ! which osc &> /dev/null; then
        init_osc
    fi
cat << END1 > /root/.oscrc
[general]
apiurl = https://euleros-obs
no_verify = 1

[https://euleros-obs]
user = root
pass = EulerOS_123
END1

    if [ "$OBSSERVER_IP" == "100.109.85.100" ];then
        OBSUI_IP="100.109.85.108"
    else
        OBSUI_IP="$OBSSERVER_IP"
    fi

    sed -i '/euleros-obs/d' /etc/hosts
    echo "$OBSSERVER_IP euleros-obs-repo.huawei.com euleros-obs-repo" >> /etc/hosts
    echo "$OBSUI_IP euleros-obs.huawei.com euleros-obs" >> /etc/hosts
    rm -f /root/.config/osc/trusted-certs/euleros-obs_443.pem
expect -c "
    set timeout -1
    spawn osc ls SUSE:SLE-11:SP3
    expect {
        \"Enter choice*\" {send \"2\r\" ; exp_continue }
        eof { catch wait result; exit [lindex \$result 3] }
     }
     expect {
         eof { catch wait result; exit [lindex \$result 3] }
     }
"
if [ $? -ne 0 ]; then
    echo "FAILED: WHEN osc ls SUSE:SLE-11:SP3"
    exit 1
fi
}

#从obs上下载最新的模块代码
function checkout_package()
{
    pro="$1"
    pack="$2"
    rm -rf "$pro"
    set +e
    osc co "$pro" "$pack"
    if [ $? -ne 0 ]; then
        sleep 60
        osc co "$pro" "$pack"
        if [ $? -ne 0 ]; then
            sleep 90
            osc co "$pro" "$pack"
            if [ $? -ne 0 ]; then
                echo "ERROR: osc co $pro $pack failed"
                exit 1
            fi
        fi
    fi
    set -e
}

#修改带_service的文件名称
function rename_obsfile()
{
    dir=$1
    pushd $dir
    set +e
    if [ -f '_service' ]; then
        osc up -S
        if [ $? -ne 0 ]; then
            sleep 60
            osc up -S
            if [ $? -ne 0 ]; then
                sleep 90
                osc up -S
                if [ $? -ne 0 ]; then
                    echo "Failed: osc up -S"
                    exit 1
                fi
            fi
        fi
        rm -rf '_service'
    fi
    set -e

    for file in `ls`
    do 
        [[ -d $file ]] && continue
        newfile=${file##_service*:}
        mv $file $newfile
    done
    popd
}

#创建编译环境
function create_buildroot()
{
    #clean obs cache
    rm -rf /var/tmp/osbuild-packagecache
    echo "clean obs cache:  rm -rf /var/tmp/osbuild-packagecache"
    prj=$1
    pkg=$2
    dir=$3
    mkdir -p $dir
    pushd $prj/$pkg
    sed  -i "/^rm -rf %{buildroot}/ d"   *.spec
    sed  -i "/^rm -rf %{_builddir}\/\*/ d" *.spec
expect -c "
     set timeout -1
     spawn osc build standard_x86_64 --root $dir
     expect {
         \"*trust packages just this time*\" {send \"1\r\";exp_continue}
         eof { catch wait result; exit [lindex \$result 3] }
     }
     expect {
         eof { catch wait result; exit [lindex \$result 3] }
     }
"
    if [ $? -ne 0 ]; then
        echo "Failed: osc build --root $dir"
        clean_build_root $dir
        exit 1
    fi
    popd
}

#配置TQE的执行环境
function tqe_conf()
{
    tqedir=$1
    dir=$2
    profile="$dir/etc/profile"
    cp -r $tqedir $dir
    if [ ! -f $profile ]; then
        echo "Failed: there is no $profile"
        exit 1
    fi
    cp -a $tqedir/../EaglEye.h $dir/
    set +e
    num=`grep -c "COV_BIN" $profile`
    set -e
    if [ $num -ne 0 ]; then
        echo "the TQE had installed"
    else
        echo "export COV_BIN=/coverity/bin" >> $profile
        echo "export PATH=\$COV_BIN:\$PATH" >> $profile
    fi
    mount --bind /proc $dir/proc
    cp -r /lib/* $dir/lib/

}

#config binscope
function binscope_conf()
{
    binscope_dir=$1
    dir=$2
    profile="$dir/etc/profile"
    cp -a $binscope_dir $dir
    cp -a $binscope_dir/../compiler-extract $dir
    chmod -R 777 $dir/binscope
    chmod -R 777 $dir/compiler-extract
    if [ ! -f $profile ]; then
        echo "Failed: there is no $profile"
        exit 1
    fi

    set +e
    num=`grep -c "BINSCOPE_BIN" $profile`
    set -e
    if [ $num -ne 0 ]; then
        echo "the BINSCOPE had been installed"
    else
        echo "export BINSCOPE_BIN=/binscope" >> $profile
        echo "export PATH=\$BINSCOPE_BIN:\$PATH" >> $profile
    fi
}

#配置fortify的执行环境
function fortify_conf()
{
    fortify_dir="$1"
    dir=$2
    profile="$dir/etc/profile"
    cp -r $fortify_dir $dir/
    cp -r $fortify_dir/../codemars_Newest $dir/
    cp -r $fortify_dir/../../7za $dir/
    cp -r $fortify_dir/../jdk1.8.0_162 $dir/

    if [ $? -ne 0 ]; then
        echo "Failed: when cp $fortify_dir to $dir/"
        exit 1
    fi
    set +e
    num=`grep -c "FORTIFY_BIN" $profile`
    set -e
    if [ $num -ne 0 ]; then
        echo "the FORTIFY had installed"
    else
        echo "export FORTIFY_BIN=/fortify/bin" >> $profile
        echo "export PATH=\$FORTIFY_BIN:\$PATH" >> $profile
    fi
    #配置codmars java的执行环境
    set +e
    jnum=`grep -c "JAVA_HOME" $profile`
    set -e
    if [ $jnum -ne 0 ] ; then
        echo "the TQE had installed"
    else
        echo "export JAVA_HOME=/jdk1.8.0_162/bin" >> $profile
        echo "export PATH=\$JAVA_HOME:\$PATH" >> $profile
    fi

    mount --bind /proc $dir/proc
    cp -r /lib/* $dir/lib/
}

function clean_build_root()
{
    dir=$1
    set +e
    umount $dir/proc
    umount $dir/dev/pts
    set -e
    rm -rf $dir
}

function clean_build_root_exit()
{
    status=$?
    dir=$1
    if [ $status -ne 0 ]; then
        set +e
        umount $dir/proc
        umount $dir/dev/pts
        set -e
        rm -rf $dir
    fi
}

function fun_main()
{
    TYPE=''
    while test $# -gt 0; do
        case $1 in
          *-project)
            PROJECT="$2"
            shift
          ;;
          *-package)
            PACKAGE="$2"
            shift
          ;;
          *-type)
            TYPE="$2"
            shift
          ;;
          *)
            echo "Unknown parameter: $1"
            echo 'Usage: env_config.sh --project $PROJECT --package $PACKAGE --type python'
            exit 1
          ;;
        esac
          shift
    done

    check_env
    mkdir -pv $CPATH
    echo "$CPATH" > project_name
    
    

    tqe_result="/usr1/tqe_result/$CI_PROJECT/$PACKAGE"
    echo $tqe_result > $CPATH/last_tqe_result
    rm -rf $tqe_result
    mkdir  -pv $tqe_result

    BUILDROOT="$CPATH/$PROJECT/$PACKAGE/build-root"
    echo $BUILDROOT > $CPATH/last_building
    trap "clean_build_root_exit $BUILDROOT" EXIT
    checkout_package "$PROJECT" "$PACKAGE"
    rename_obsfile "$PROJECT/$PACKAGE"
    clean_build_root $BUILDROOT
    create_buildroot $PROJECT $PACKAGE $BUILDROOT

    if [ ! -d $TQEDIR ]; then
        echo "Failed: There is no TQE dir"
        exit 1
    fi
    tqe_conf $TQEDIR $BUILDROOT
    #fortify_conf $FORTIFYDIR $BUILDROOT
    #binscope_conf $BINSCOPEDIR $BUILDROOT

    #执行cov make的动作
    #ln是解决uname -r获取内核版本号不对的问题，如果不是内核模块下面的可能会执行失败，但是不影响
    if [ ! -f $BUILDROOT/.build.log ]; then
        echo "Failed:osc build error"
        exit 1
    fi
    rpmbuild_dir=`cat $BUILDROOT/.build.log  | grep '.src.rpm' | awk '{print $NF}' | sed 's/[ :]//g' | awk -F'SRPMS' '{print $1}'`
    echo "$TYPE" > "$CPATH/last_build_type"
    if [ "x$TYPE" == "x" -o "$TYPE" == "cplus" ]; then
        if [ $PACKAGE == "ltran" ];then
            create_ltran_make "$rpmbuild_dir"
        else
            create_make "$rpmbuild_dir"
        fi
    else
        echo "--type $TYPE cant not recongsize"
        exit 1
    fi
    mv do_make.sh $BUILDROOT/
    exit 0
}

function create_make()
{
rpmbuild_dir=$1

if [ -d $BUILDROOT/home/abuild/rpmbuild/BUILD ] ;then
  PACKAGE_DIR=`ls -F $BUILDROOT/home/abuild/rpmbuild/BUILD/ | grep '/$'`
  cov_dir=/home/abuild/rpmbuild/BUILD/
else
  PACKAGE_DIR=`ls -F $BUILDROOT/root/rpmbuild/BUILD/ | grep '/$'`
  cov_dir=/root/rpmbuild/BUILD/
fi

cat <<END1 > do_make.sh
kernel_ver=`uname -r`
rm -rf /lib/modules/\${kernel_ver}
ln -s /lib/modules/*-default /lib/modules/\${kernel_ver}
source /etc/profile
cd $rpmbuild_dir/BUILD/\$1
if [ \$1 == 'hotpatchrec-1.0/rechandler' ];then
    cd ..
    rm -f CMakeCache.txt
fi
make clean
find $rpmbuild_dir/BUILD/ -name "*.o" | xargs rm -f
cov-build --dir cov make \$2
tqe_result=\$?
echo \$tqe_result > /tqe_make_result
mv ./cov $rpmbuild_dir/BUILD/

if [ \$1 == 'hotpatchrec-1.0/rechandler' ];then
    cmake .
    rm -f CMakeCache.txt
fi
make clean
find $rpmbuild_dir/BUILD/ -name "*.o" | xargs rm -f
cp /EaglEye.h /coverity/config
cov-build --dir eaglEye make \$2
eagleye_result=\$?
echo \$eagleye_result > /eagleye_make_result
mv ./eaglEye $rpmbuild_dir/BUILD/

END1
}

function create_ltran_make()
{
rpmbuild_dir=$1

if [ -d $BUILDROOT/home/abuild/rpmbuild/BUILD ] ;then
  PACKAGE_DIR=`ls -F $BUILDROOT/home/abuild/rpmbuild/BUILD/ | grep '/$'`
  cov_dir=/home/abuild/rpmbuild/BUILD/
else
  PACKAGE_DIR=`ls -F $BUILDROOT/root/rpmbuild/BUILD/ | grep '/$'`
  cov_dir=/root/rpmbuild/BUILD/
fi

cat <<END1 > do_make.sh
LIB_PATH=/home/abuild/rpmbuild/BUILD/ltran-1.0.0/dpdk_static
export DPDK_INCLUDE_FILE=/usr/include/dpdk
export ARCH_TARGET=x86
export RTE_TARGET=x86_64-native-linuxapp-gcc
export RTE_SDK=/usr/share/dpdk
export MAKE_TARGET=use_libos_memory
export LIBOS_MEM_SDK=/usr/include/dpdk
export LIBOS_MEM_LIB_FILE=/home/abuild/rpmbuild/BUILD/ltran-1.0.0/dpdk_static
export LIBOS_CONFIG_SDK=/usr/include/dpdk
export LIBOS_CONFIG_SDK_LIB=/home/abuild/rpmbuild/BUILD/ltran-1.0.0/dpdk_static
export LIBOS_LOG_LIB_FILE=/home/abuild/rpmbuild/BUILD/ltran-1.0.0/dpdk_static
export LIBOS_LOG_SDK=/usr/include/dpdk
kernel_ver=`uname -r`
rm -rf /lib/modules/\${kernel_ver}
ln -s /lib/modules/*-default /lib/modules/\${kernel_ver}
source /etc/profile
cd $rpmbuild_dir/BUILD/\$1
make clean
find $rpmbuild_dir/BUILD/ -name "*.o" | xargs rm -f
cov-build --dir cov make \$2
tqe_result=\$?
echo \$tqe_result > /tqe_make_result
mv ./cov $rpmbuild_dir/BUILD/

make clean
find $rpmbuild_dir/BUILD/ -name "*.o" | xargs rm -f
cp /EaglEye.h /coverity/config
cov-build --dir eaglEye make \$2
eagleye_result=\$?
echo \$eagleye_result > /eagleye_make_result
mv ./eaglEye $rpmbuild_dir/BUILD/

END1
}


fun_main $@
